package com.dk.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @Description
 * @ClassName LoginController
 * @Author RC
 * @date 2020.12.07 15:01
 */
@Controller
public class LoginController {

    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }

    @RequestMapping("login")
    public String login(String userName, String password, Model model){
        //获取用户主体 subject
        Subject subject = SecurityUtils.getSubject();
        //将表单提交的账号和密码封装成token对象
        UsernamePasswordToken token = new UsernamePasswordToken(userName,password);
        //执行登录逻辑
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            //账号不存在提示
            model.addAttribute("message","账号不存在");
            return "login";
        }catch (IncorrectCredentialsException e){
            //密码错误提示
            model.addAttribute("message","密码错误");
            return "login";
        }
        return "redirect:/index";
    }
    @RequestMapping("unauthorized")
    public String unauthorized(){
        return "unauthorized";
    }

}
